package com.bwie.filter;

import io.jsonwebtoken.Jwts;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author DarkClown
 * @date 2024-07-23 09:13
 * @project_name week0723
 * @parem
 **/
@Configuration
public class MyGlobalFilter implements GlobalFilter, Ordered {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String token = request.getHeaders().getFirst("token");

        if (StringUtils.isEmpty(token)){
            boolean b = response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        Integer uid = Jwts.parser().setSigningKey("123456")
                .parseClaimsJws(token)
                .getBody().get("uid", Integer.class);

        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();

        String s = opsForValue.get("token" + uid);

        if (StringUtils.isEmpty(s)){
            boolean b = response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
